<template>
  <div class="addGroup">
    <el-dialog
      :visible="visible"
      :close-on-click-modal="false"
      width="520px"
      :modal-append-to-body="false"
      :show-close="false"
    >
      <div slot="title" class="header">
        <div class="left">
          <div class="icon" />
          <div class="title">修改用户</div>
        </div>
        <div class="close_icon" @click="close" />
      </div>
      <el-form ref="accountForm" label-width="80px" :model="accountForm" :rules="rules">
        <el-form-item prop="account" label="账号">
          <el-input
            v-model="accountForm.account"
            disabled
            type="text"
            placeholder="请输入账号"
          />
        </el-form-item>
        <el-form-item prop="real_name" label="真实姓名">
          <el-input
            v-model="accountForm.real_name"
            type="text"
            placeholder="请输入真实姓名"
          />
        </el-form-item>
        <el-form-item prop="accountPwd" label="密码">
          <el-input
            ref="accountPwd"
            v-model="accountForm.accountPwd"
            :type="password_type"
            placeholder="请输入密码"
          >
            <div slot="suffix" :class="password_type ? 'hide_pwd_icon' : 'show_pwd_icon'" @click="showPwd" />
          </el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input
            v-model="accountForm.email"
            placeholder="请输入邮箱"
          />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="accountForm.role_id" placeholder="请选择角色">
            <el-option v-for="(item, index) in roleList" :key="index" :label="item.role_name_zh" :value="item.role_id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="footer">
        <el-button class="btn" plain @click="close">取消</el-button>
        <el-button class="btn" type="primary" :loading="loading" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const sha256 = require('js-sha256').sha256
import { account_update } from '@/api/account'
import { role_list } from '@/api/role'
export default {
  name: 'AccountEdit',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    checkData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value) {
        if (value.length < 8 || value.length > 16) {
          callback(new Error('密码长度不能少于8位，且不能超过16位'))
        } else {
          if (!/[a-zA-Z]+(?=\d+)|\d+(?=[a-zA-Z]+)/g.test(value)) {
            callback(new Error('密码必须同时包含字母、数字'))
          }
          callback()
        }
      }
      callback()
    }
    // 这里存放数据
    return {
      loading: false,
      roleList: [],
      accountForm: {
        account: '',
        accountPwd: '',
        email: '',
        real_name: '',
        role_id: ''
      },
      rules: {
        account: { required: true, message: '请输入账号', trigger: 'blur' },
        real_name: { required: true, message: '请输入真实姓名', trigger: 'blur' },
        accountPwd: [{ validator: validatePassword, trigger: 'blur' }]
      },
      password_type: 'password'
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    visible(n, o) {
      if (n) {
        this.accountForm.account = this.checkData.account
        this.accountForm.email = this.checkData.email
        this.accountForm.real_name	 = this.checkData.real_name
        this.accountForm.role_id = this.checkData.role_id
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  async created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.loadRole()
  },
  // 生命周期 - keep-alive
  async activated() {},
  // 方法集合
  methods: {
    submit() {
      this.$refs.accountForm.validate(async(valid) => {
        if (valid) {
          try {
            this.loading = true
            const param = Object.assign({}, this.accountForm)
            param.accountPwd = param.accountPwd ? sha256(param.accountPwd) : undefined
            param.email = param.email ? param.email : undefined
            delete param['roleId']
            const { code } = await account_update(this.accountForm.account, param)
            if (!code) {
              this.close()
              this.$parent.loadData()
              this.$messageOnce.success('操作成功！')
            }
          } catch (error) {
            console.error(error)
          } finally {
            this.loading = false
          }
        }
      })
    },
    async loadRole() {
      const { code, data } = await role_list()
      if (!code) {
        this.roleList = data
        this.accountForm.roleId = data[0].role_id
      } else {
        this.$messageOnce.error('获取角色列表失败')
      }
    },
    showPwd() {
      if (this.password_type === 'password') {
        this.password_type = ''
      } else {
        this.password_type = 'password'
      }
      this.$nextTick(() => {
        this.$refs.accountPwd.focus()
      })
    },
    close() {
      this.$refs.accountForm.resetFields()
      this.$emit('close')
    }
  },
  // 进入页面前
  beforeRouteEnter(to, from, next) {
    next((vm) => {})
  },
  // 离开页面前
  beforeRouteLeave(to, from, next) {
    next()
  }
}
</script>
<style lang="scss" scoped>
.addGroup {
	.header{
		width: 100%;
		display: flex;
		justify-content: space-between;
    align-items: center;
    background: #FAFAFA;
		.left{
			display: flex;
			.icon{
				background: url('../../assets/dialog/edit_icon.png');
				@include dialog_head_icons;
			}
			.title{
				font-size: 14px;
				font-family: SourceHanSansCN-Medium, SourceHanSansCN;
				font-weight: 500;
				color: #000000;
				line-height: 30px;
			}
		}
    .close_icon {
				width:25px;
        height: 24px;
				background: url('../../assets/close-icon.png');
				background-size: 100%;
        cursor: pointer;
		}
	}
  .footer {
    text-align: center;
    .btn{
      width: 80px;
    }
  }
}

.show_pwd_icon {
	width: 16px;
	height: 14px;
	background: url('../../assets/login/show_pwd.png');
	background-size: 100%;
	margin-right: 10px;
	margin-top: 12px;
	cursor: pointer;
}

.hide_pwd_icon {
	width: 16px;
	height: 8px;
	background: url('../../assets/login/hide_pwd.png');
	background-size: 100%;
	margin-right: 10px;
	margin-top: 17px;
	cursor: pointer;
}

::v-deep .el-dialog__body {
    padding: 25px 30px 30px 30px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
}

::v-deep .el-dialog__footer{
  height: 80px;
  padding: 20px;
  box-shadow: 0px -5px 20px 0px rgba(71, 73, 155, 0.06);
  border-radius: 0px 0px 4px 4px;
}
</style>
